package controllers

import (
	"fmt"
//	"github.com/astaxie/beego"
	"blog/models"
	"github.com/astaxie/beego/orm"
	"time"
	"github.com/astaxie/beego/validation"
)

type MemberController struct {
	baseController
}

func (c *MemberController) Reg() {
	c.TplNames = "reg.tpl"
	u := models.User{}
	err := c.ParseForm(&u)
	valid:=validation.Validation{}
	valid.Required(u.Name,"name.用户名")
	valid.Required(u.Pass,"pass.密码")
	valid.Email(u.Email,"email.邮箱")
	valid.Phone(u.Phone,"phone.电话")
	if valid.HasErrors(){
		c.Data["errors"]=valid.Errors
		c.Data["errsMap"]=valid.ErrorsMap
		fmt.Println(valid.ErrorsMap["name"].Message)
		 for _, err := range valid.Errors {
            fmt.Println(err.Key, err.Message)
        }
		return
	}
	u.CreateDate=time.Now().UnixNano()
	fmt.Print("ERROR:",u.Name,"\r\n")
    if err == nil {
		fmt.Print("ID:",u.Id,"\r\n")
		fmt.Print("Name:"+u.Name,"\r\n")
		fmt.Print("Email:"+u.Email,"\r\n")
		fmt.Print("Pass:"+u.Pass,"\r\n")
		fmt.Print("Phone:"+u.Phone,"\r\n")
		fmt.Print("CreateDate:",u.CreateDate,"\r\n")
		o := orm.NewOrm()
	    o.Using("default") // 默认使用 default，你可以指定为其他数据库
		// 数据库别名
		name := "default"
		
		// drop table 后再建表
		force := false
		
		// 打印执行过程
		verbose := true
		
		// 遇到错误立即返回
		err := orm.RunSyncdb(name, force, verbose)
	if err != nil {
	    fmt.Println(err)
	}
	    fmt.Println(o.Insert(&u))
		
		
        //handle error
    }else{
		fmt.Print("SomeError",err,"\r\n")
	}
}

func (c *MemberController) Login(){
	c.TplNames = "login.tpl"
	u := models.User{}
	er := c.ParseForm(&u)
	
	if er==nil{
		 fmt.Println("\r\n","数据解析成功：",&u)
		o := orm.NewOrm()
		    o.Using("default") // 默认使用 default，你可以指定为其他数据库
			// 数据库别名
			name := "default"
			
			// drop table 后再建表
			force := false
			
			// 打印执行过程
			verbose := true
			
			// 遇到错误立即返回
			err := orm.RunSyncdb(name, force, verbose)
		if err != nil {
		    fmt.Println("\r\n",err)
		}
		ex := o.QueryTable("user").Filter("Name",&u.Name).Filter("Pass",&u.Pass).One(&u)
		
		if ex == orm.ErrMultiRows {
			c.SetSession("isLogin",true)
		    // 多条的时候报错
		   			fmt.Printf("\r\n","找到多条记录")
		}
		if ex == orm.ErrNoRows {
		    // 没有找到记录
		    fmt.Printf("\r\n","没有找到记录")
		}else{
			c.SetSession("isLogin",true)
			fmt.Printf("\r\n","登陆成功！")
		}
	    fmt.Println("\r\n",&u)
	}else{
	 fmt.Println("\r\n",er)
	}
}

func(c *MemberController) Logout(){
	
}
func init(){
		fmt.Print("当前文件member.go","\r\n")
}